package love.yuanmengrobot.als.business.servlet;

import love.yuanmengrobot.als.business.dao.SearchScoreInfoDao;
import love.yuanmengrobot.als.business.dao.ReadStudentScoreDao;
import love.yuanmengrobot.als.business.dao.impl.ReadStudentScoreDaoImpl;
import love.yuanmengrobot.als.business.dao.impl.SearchScoreInfoDaoImpl;
import love.yuanmengrobot.als.business.javaBean.ScoreView;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class importDataScoreServlet extends HttpServlet {
    private List<String> fileList;
    private SearchScoreInfoDao searchScoreInfoDao;
    private int allPage;
    private int pageNow;
    private String searchStu;
    private String searchName;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (doPostURI(request, response))
            doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGetURI(request, response);
        request.getRequestDispatcher("WEB-INF/view/business/importDataScore/importDataScore.jsp").forward(request, response);
    }

    /**
     * 查找遍历文件夹中所有文件
     *
     * @param list 文件或文件夹
     */
    private void outFiles(File list) {
        if (list.isDirectory()) {//检测到根存在分支
            File[] files = list.listFiles();//将根变成数组，遍历根的分支
            assert files != null;
            for (File file : files) {//该for循环导致outFiles方法会检索到该层文件夹的所有文件与文件夹
                outFiles(file);//进入新的文件根地址
            }
        } else {
            if (list.getName().endsWith(".xls") || list.getName().endsWith(".xlsx")) {
                fileList.add(list.getName());
            }
        }
    }

    /**
     * 删除文件
     *
     * @param list     文件
     * @param fileName 需要删除的文件名
     * @return 是否删除
     */
    private boolean deleteFiles(File list, String fileName) {
        if (list.isDirectory()) {//检测到根存在分支
            File[] files = list.listFiles();//将根变成数组，遍历根的分支
            assert files != null;
            for (File file : files) {//该for循环导致outFiles方法会检索到该层文件夹的所有文件与文件夹
                if (deleteFiles(file, fileName)) {
                    break;
                }
            }
        } else {
            if (list.getName().equals(fileName)) {
                if (list.delete()) {
                    System.out.println("delete");//删除文件
                } else System.out.println("Delete Fail");
                return true;
            } else System.out.println("noEquals");
        }
        return false;
    }

    /**
     * 上传文件
     *
     * @param request  request
     * @param response response
     * @return void
     * @throws IOException IO
     */
    private int uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return 0;
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();// 配置上传参数
        factory.setSizeThreshold(1024 * 1024 * 3);// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));// 设置临时存储目录

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setFileSizeMax(1024 * 1024 * 40);// 设置最大文件上传值
        upload.setSizeMax(1024 * 1024 * 50);// 设置最大请求值 (包含文件和表单数据)
        upload.setHeaderEncoding("UTF-8");// 中文处理

        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        String uploadPath = request.getServletContext().getRealPath("./") + File.separator + "upload";

        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            if (uploadDir.mkdir()) {
                System.out.println("create folder");// 如果目录不存在则创建
            }
        }

        try {
            // 解析请求的内容提取文件数据
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        if ("".endsWith(fileName)) {
                            return -2;
                        } else if (!(fileName.endsWith(".xls") || fileName.endsWith(".xlsx"))) {
                            return -1;
                        }

                        String filePath = uploadPath + File.separator + fileName;
                        String filePath2 = uploadPath + File.separator + fileName;
                        filePath2 = filePath2.replace("\\\\", "\\");
                        filePath2 = filePath2.replace("\\", "\\\\");
                        File storeFile = new File(filePath);
                        System.out.println(storeFile.getName());
                        System.out.println("file1" + filePath);
                        System.out.println("file2" + filePath2);
                        // 保存文件到硬盘
                        item.write(storeFile);
                        ReadStudentScoreDao rss = new ReadStudentScoreDaoImpl();
                        rss.getAllInfo(filePath2);

                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message", "错误信息: " + ex.getMessage());
        }
        return 1;
    }

    /**
     * 输出错误信息到前端
     *
     * @param request   request对象
     * @param errorFlag 错误标志
     */
    private void uploadError(HttpServletRequest request, int errorFlag) {
        if (errorFlag == -1) {
            request.setAttribute("errorMes", "文件不是Excel");
        } else if (errorFlag == -2) {
            request.setAttribute("errorMes", "请选择要上传的文件");
        }
    }

    private File getUploadFile(HttpServletRequest request) {
        String uploadPath = request.getServletContext().getRealPath("./") + File.separator + "upload";
        uploadPath = uploadPath.replace("\\\\", "\\");
        uploadPath = uploadPath.replace("\\", "\\\\");
        return new File(uploadPath);
    }

//    private File getUploadFile(HttpServletRequest request, String fileName) {
//        String uploadPath = request.getServletContext().getRealPath("./") + File.separator + "upload" + File.separator + fileName;
//        uploadPath = uploadPath.replace("\\\\", "\\");
//        uploadPath = uploadPath.replace("\\", "\\\\");
//        return new File(uploadPath);
//    }

    /**
     * 处理doGet的URI请求
     *
     * @param request request对象
     */
    private void doGetURI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        System.out.println("get" + uri);
        if (request.getParameter("id") != null) {
            System.out.println(request.getParameter("id"));
        }
        fileList = new ArrayList<>();
        File file = getUploadFile(request);
        outFiles(file);

        request.setAttribute("file", fileList);
        if (uri.contains("search")) {
            if (uri.contains("searchLast") || uri.contains("searchNext")) {
                pageNow = Integer.parseInt(request.getParameter("pageNow"));
                if (uri.contains("searchLast")) {
                    if (pageNow != 1) {
                        pageNow--;
                    }
                } else if (uri.contains("searchNext")) {
                    if (pageNow < allPage) {
                        pageNow++;
                    }
                }
            } else if (uri.contains("searchPage")) {
                pageNow = Integer.parseInt(request.getParameter("setPage"));
            }
            List<ScoreView> views = searchScoreInfoDao.searchScoreInfo(searchStu, searchName, pageNow);
            request.setAttribute("scoreView", views);
            request.setAttribute("pageNow", pageNow);
            request.setAttribute("allPage", allPage);
        } else if (uri.contains("deleteScore")) {
            searchScoreInfoDao.deleteScore(request.getParameter("score_id"));
            request.getRequestDispatcher("/searchNow").forward(request, response);
        } else if (uri.contains("updateScore")) {
            request.setAttribute("idUpdate", request.getParameter("idUpdate"));
            request.setAttribute("stuNoUpdate", request.getParameter("stuNoUpdate"));
            request.setAttribute("nameUpdate", request.getParameter("nameUpdate"));
            request.setAttribute("scoreUpdate", request.getParameter("scoreUpdate"));
        }

    }

    /**
     * 处理doPost的URI请求
     *
     * @param request  request对象
     * @param response response对象
     * @throws IOException 异常
     */
    private boolean doPostURI(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        String uri = request.getRequestURI();
        System.out.println("post" + uri);

        if (uri.contains("upload")) {
            uploadError(request, uploadFile(request, response));//如果有错,输出错误信息在网页
        } else if (uri.contains("deleteFile")) {
            File file = getUploadFile(request);
            String[] checkbox = request.getParameterValues("checkbox");
            if (checkbox != null) {
                for (String s : checkbox) {
                    deleteFiles(file, s);
                }
            }
        } else if (uri.endsWith("search")) {
            searchScoreInfoDao = new SearchScoreInfoDaoImpl();
            pageNow = 1;
            searchStu = request.getParameter("stu");
            searchName = request.getParameter("name");
            allPage = searchScoreInfoDao.getAllPage(searchStu, searchName);
        } else if (uri.contains("updateScore")) {
            boolean flag = false;
            String score = request.getParameter("scoreUpdate");
            int number = Integer.parseInt(score);
            if ("及格".equals(score) || "优".equals(score) || "良".equals(score) || "中".equals(score) || "合格".equals(score)
                    || "不及格".equals(score) || "旷考".equals(score) || "取消".equals(score) || "不合格".equals(score)) {
                flag = true;
            } else if (number >= 0 && number <= 100) {
                flag = true;
            }
            if (flag) {
                searchScoreInfoDao.updateScore(request.getParameter("idUpdate"), score);
            }
            request.getRequestDispatcher("/searchNow").forward(request, response);
            return false;
        }
        return true;
    }
}
